<template>
  <div class="editor-box">
    <div style="border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        style="height: 300px"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
      />
    </div>
  </div>
</template>

<script setup lang="ts" name="Editor">
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { onBeforeUnmount, ref, shallowRef, computed } from 'vue'

type InsertFnType = (url: string, alt: string, href: string) => void

const emits = defineEmits(['update:modelValue'])
const props = defineProps(['modelValue'])

const mode = ref('default') //'default' or 'simple'
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

const valueHtml = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emits('update:modelValue', value)
  },
})

const toolbarConfig = {
  excludeKeys: ['group-video', 'insertVideo'],
}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      fieldName: 'file',
      server: import.meta.env.VITE_APP_BASE_API + '/oss/upload',
      base64LimitSize: 5 * 1024, // 5kb
      customInsert(res: any, insertFn: InsertFnType) {
        if (res.code == 200) {
          insertFn(res.data.url, res.data.filename, res.data.url)
        } else {
          ElMessage.error(res.message)
        }
      },
    },
  },
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return

  editor.destroy()
})

const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
</script>

<style lang="scss" scoped>
.editor-box {
  display: flex;
}
p {
  word-wrap: break-word;
}
</style>
